/*
 * @Author: yangzonglong
 * @Date: 2021-05-25 14:43:54
 * @version: v1.0.0
 * @Descripttion: table
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-10-19 15:22:39
 * @Auditor:
 */
import React, { useState, useImperativeHandle, forwardRef, useEffect, useMemo } from 'react';
import { Flex, Toast } from 'antd-mobile';
// import update from 'immutability-helper';
import empty from './empty.svg';

import styles from './table.module.scss';

const _Column = require('./Column');
const Column = _Column['default'];
const rowStyle = {
  marginBottom: '0',
  lineHeight: '48px',
  height: '48px',
  padding: '0 4px',
};
const tbStyle = { padding: '0 16px', background: '#fff' };

const Table = (props) => {
  let children = props.children || [];

  return (
    <div className={styles.mbTable} id="mbTable">
      {!props?.dataSource?.length ? (
        <table className={styles.emptytable}>
          <thead className={styles.anttablethead}>
            <tr>
              {children.map((ele) => (
                <th key={ele.key} style={ele?.props?.width && props.isScroll ? { width: ele?.props?.width + 'px' } : { flex: '1 1' }}>
                  {ele?.props?.title}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>
                <img src={empty} alt="" />
                <p>暂无数据</p>
              </td>
            </tr>
          </tbody>
        </table>
      ) : (
        <table className={styles.table}>
          <thead className={styles.anttablethead}>
            <tr>
              {children.map((ele) => (
                <th key={ele.key} style={ele?.props?.width && props.isScroll ? { width: ele?.props?.width + 'px' } : { flex: '1 1' }}>
                  {ele?.props?.title}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {props?.dataSource?.map((data, index) => {
              return (
                <tr key={data.id}>
                  {children.map((ele) => (
                    <td key={ele.key} style={ele?.props?.width && props.isScroll ? { width: ele?.props?.width + 'px' } : { flex: '1 1' }}>
                      {ele?.props?.render?.(data, data, index)}
                    </td>
                  ))}
                </tr>
              );
            })}
          </tbody>
        </table>
      )}
    </div>
  );
};

export default forwardRef((props, ref) => {
  const { tableProps, title, initialValue } = props;

  const [dataSource, setDataSource] = useState([]);
  const [isScroll, setIsScroll] = useState(false);

  useImperativeHandle(ref, () => ({
    getData() {
      const handleDataSource = [];
      const requiredColumns = props.tableProps.columns.filter((item) => item.options.required);

      for (let item of dataSource) {
        const copyItem = { ...item, _isEdit: false };

        requiredColumns.forEach((column) => {
          if (!copyItem[column.dataIndex]) {
            copyItem[column.dataIndex] = column.options.initialValue;
          }
        });

        for (let k in copyItem) {
          const column = props.tableProps.columns.find((item) => item.dataIndex === k);

          // 必填项校验
          if (column?.options.required && !copyItem[k]) {
            Toast.info('请完整填表格');
            return false;
          }
        }

        handleDataSource.push(copyItem);
      }

      return handleDataSource;
    },
  }));

  useEffect(() => {
    if (initialValue) setDataSource(initialValue);
  }, [initialValue]);

  useEffect(() => {
    setIsScroll(props.tableProps.columns.length > 1);
  }, [props.tableProps.columns]);

  // const onChangeLine = (record, v, k) => {
  //   const index = dataSource.findIndex((item) => item.id === record.id);
  //   setDataSource(
  //     update(dataSource, {
  //       [index]: {
  //         [k]: {
  //           $set: v,
  //         },
  //       },
  //     })
  //   );
  // };

  const render = (text, record, column) => {
    // const dataIndex = column.dataIndex;
    const options = column.options;

    let value = record[column.dataIndex];

    if (column.type === 'radio' || column.type === 'checkbox') {
      let _dataSource = options?.options?.dataSource;
      let _item = _dataSource.filter((item) => item.value === options.value);
      value = _item?.[0]?.['label'];
    } else {
      const showFieldName = options?.showFieldName;
      if (showFieldName) value = value?.[showFieldName];
    }

    return <div>{value || '-'}</div>;
  };

  const columns = useMemo(() => {
    if (tableProps.showItemNo) {
      const itemColumn = [
        {
          dataIndex: 'itemNo',
          width: 100,
          title: '行号',
          render: (text, record, index) => <span>{(index + 1) * 10}</span>,
        },
      ];
      return itemColumn.concat(tableProps.columns);
    }

    return tableProps.columns;
  }, [tableProps.showItemNo, tableProps.columns]);

  return (
    <div style={tbStyle}>
      <Flex justify="between" align="center" style={rowStyle}>
        {title}
      </Flex>

      <Table dataSource={dataSource} isScroll={isScroll} rowk>
        {columns.map((item) => (
          <Column
            key={item.dataIndex}
            width={item.width * 2}
            title={item.title}
            render={(text, record, index) => {
              if (item.render) return item.render(text, record, index);
              return render(text, record, item);
            }}
          />
        ))}
      </Table>
    </div>
  );
});
